home *** CD-ROM | disk | FTP | other *** search
- Path: crl.crl.com!not-for-mail
- From: bobfry@crl.com (Robert Fry)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: 19 Jan 1996 15:10:19 -0800
- Organization: CRL Dialup Internet Access
- Message-ID: <4dp8cr$sit@crl.crl.com>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dorr8$i58@cloner3.netcom.com> <ALUN.CHAMPION.96Jan19170141@g7240065.bridge.bst.bls.com>
- NNTP-Posting-Host: crl.com
-
- Someone was asking for a quick way to determine if a number is a power of
- 2. The solutions I've seen involved ounting every bit and seeing if the
- number of 'on' bits is 1. But why not take advantage of the binary
- representation of numbers and use:
-
- int is_power_of_2( long num)
- {
- return((( num - 1) & num) == 0);
- }
-
- (You could also make a macro of it if you need better speed in exchange
- for reduced maintainability):
-
- #define IS_POWER_OF_2(num) (!(( num - 1) & num))
-
- Be careful with this, of course. IS_POWER_OF_2(x++) has undefined results,
- for example.
-
- Bob
-